package org.thinkinbunny.financial.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;
import org.thinkinbunny.financial.R;
import org.thinkinbunny.financial.billentity.BillEntiry;
import org.thinkinbunny.financial.data.DbHelper;
import org.thinkinbunny.financial.http.HttpTools;
import org.thinkinbunny.financial.login.LoginActivity;
import org.thinkinbunny.financial.util.Constant;
import org.thinkinbunny.financial.util.Log;
import org.thinkinbunny.financial.util.DateUtil;
import org.thinkinbunny.financial.util.ShowTools;
import org.thinkinbunny.financial.view.AutoAdjustTextView;
import org.thinkinbunny.financial.view.ListViewAdapter;
import org.thinkinbunny.financial.view.ShowDialog;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Looper;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ListView;

/**
 * 
 * 
 * @author yfxiawei
 * @since 2012-2-22
 */
public class MainActivity extends MyActivity {
	ImageButton quickWriteBill_BTN;
	Button writeBill_btn;
	ImageButton recoder_BTN;
	ImageButton message_BTN;
	ListView billListView;
	ListViewAdapter listViewAdapter;
	AutoAdjustTextView spending_this_month, spending_this_week;
	Cursor cursor;
	DbHelper dbHelper;// =new DbHelper(getApplicationContext(),
	// DbHelper.dBString);
	SQLiteDatabase database;// =dbHelper.getWritableDatabase();
	Dialog updatedialog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		setupViews();
		registerForContextMenu(billListView);

//		quickWriteBill_BTN.setOnClickListener(this);
//		writeBill_btn.setOnClickListener(this);
//		recoder_BTN.setOnClickListener(this);
//		message_BTN.setOnClickListener(this);

		// SimpleDateFormat dateformat = new
		// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		// // initData();
		// //
		// " balancedate INTEGER DEFAULT 0, hasbalance INTEGER DEFAULT 0, warningbalance decimal(10,2) DEFAULT 0,"
		// +
		// // " haswarning INTEGER DEFAULT 0, moneytype INTEGER DEFAULT 1, star
		// INTEGER DEFAULT 0
		// ContentValues contentValues=new ContentValues();
		// contentValues.put("_id",
		// SystemClock.currentThreadTimeMillis());//balancedate
		// contentValues.put("name", "test"+(int)(Math.random()*100));
		// contentValues.put("type", 1);
		// contentValues.put("balance", (int)(Math.random()*100));
		// contentValues.put("hasbalance", 1);
		// contentValues.put("moneytype", 100);
		// contentValues.put("star", 100);
		// contentValues.put("time",JDTime.getTimeWithSecond());

		// long a= database.insert("ACCOUNTINFO", null, contentValues);

		// billListView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
		// R.layout.listview_showbill_basic, null));
		DoCheck();

	}

	void saveBudget(float weekbill, float monthbill) {
		try {
			Log.i("xiawei", weekbill+"saveBudget"+monthbill);
			SharedPreferences pref = getSharedPreferences(Constant.BUDGET_SHARE,
					Context.MODE_PRIVATE);
			Editor editor = pref.edit();
			editor.putFloat("weekbill", weekbill);
			editor.putFloat("monthbill", monthbill);
			
			editor.commit();
			if (pref.getInt("weekBudget", 0)<(int)weekbill||pref.getInt("weekBudget",0)<(int)monthbill) {
				ShowTools.toastInThread(getString(R.string.budget_more_error));
				
			}
		} catch (Exception e) {
			// TODO: handle exception
		}

	}

	public void initData(SQLiteDatabase database) {
		// database=dbHelper.getWritableDatabase();
		Cursor cursor = database.rawQuery("select * from accountInfo", null);
		ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();

		listViewAdapter = new ListViewAdapter(getApplicationContext(),
				R.layout.list_items, cursor, new String[] { "balance",
						"billType", "date", "time" }, new int[] {
						R.id.billMoneyTextView, R.id.billTypeTextView,
						R.id.billTimeTextView });
		// 添加并且显示
		billListView.setAdapter(listViewAdapter);
		final Cursor getCursor = cursor;
		float balance = 0;
		float monthBalance = 0;
		ArrayList week = DateUtil.getWeekBill();
		while (getCursor.moveToNext()) {
			if (week.contains(getCursor.getString(getCursor
					.getColumnIndex("date")))) {
				balance += getCursor.getFloat(getCursor
						.getColumnIndex("balance"));
				Log.i("xiawei", balance+"weekbill"+getCursor.getFloat(getCursor
						.getColumnIndex("balance")));
			}
			
			Log.i("xiawei", balance+"balance"+getCursor.getFloat(getCursor
					.getColumnIndex("balance")));
			
			if (getCursor.getString(getCursor.getColumnIndex("date"))
					.startsWith(DateUtil.getMonthBill())) {
				monthBalance += getCursor.getFloat(getCursor
						.getColumnIndex("balance"));
			}

		}
		spending_this_week.setText(balance + "￥");
		spending_this_month.setText(monthBalance + "￥");
		saveBudget(balance, monthBalance);
	//	balance = 0.0f;
		//monthBalance = 0.0f;
		// 添加点击
		billListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int id,
					long arg3) {

				// getCursor.moveToPosition(id);

				BillEntiry billEntiry = (BillEntiry) listViewAdapter
						.getItem(id);
				Intent intent = new Intent(MainActivity.this,
						NewBillActivity.class);
				Bundle bundle = new Bundle();
				bundle.putSerializable("entirty", billEntiry);
				intent.putExtra("entirtyBundle", bundle);
				startActivity(intent);
			}
		});

		// billListView.setOnCreateContextMenuListener(new
		// OnCreateContextMenuListener() {
		//
		// public void onCreateContextMenu(ContextMenu menu, View
		// v,ContextMenuInfo menuInfo) {
		// menu.setHeaderTitle("账单操作");
		// menu.add(0, 0, 0, "删除");
		// menu.add(0, 1, 0, "编辑");
		// }
		//
		//
		// });

	}
	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		// super.onResume();

		// cursor=database.rawQuery("select * from ACCOUNTINFO",
		// null);//database.execSQL("select * from ACCOUNTINFO");
		dbHelper = new DbHelper(getApplicationContext(), DbHelper.DbName);
		database = dbHelper.getWritableDatabase();
		initData(database);
		database.close();

		super.onResume();

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		// TODO Auto-generated method stub

		menu.setHeaderTitle(getString(R.string.bill_Manger));
		menu.add(0, 0, 0, getString(R.string.bill_drop));
		menu.add(0, 1, 0, getString(R.string.bill_edit));
		// super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item
				.getMenuInfo();
		long id = menuInfo.id;
		if (item.getTitle() == getString(R.string.bill_drop)) {
			BillEntiry billEntiry = (BillEntiry) listViewAdapter
					.getItem((int) id);
			boolean flag = DbHelper.dropBillById(getApplicationContext(),
					billEntiry.get_id());
			if (flag) {
				ShowTools.toast("ok");
				database = dbHelper.getWritableDatabase();
				initData(database);
				listViewAdapter.notifyDataSetInvalidated();
				listViewAdapter.notifyDataSetChanged();
			} else {
				ShowTools.toast("error");
			}
		} else {

			BillEntiry billEntiry = (BillEntiry) listViewAdapter
					.getItem((int) id);
			Intent intent = new Intent(MainActivity.this, NewBillActivity.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("entirty", billEntiry);
			intent.putExtra("entirtyBundle", bundle);
			startActivity(intent);

		}
		return super.onContextItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onNewIntent(Intent intent) {
		// TODO Auto-generated method stub
		super.onNewIntent(intent);
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	private void setupViews() {
		findViewById(R.id.btnDetails).setOnClickListener(this);
		findViewById(R.id.UserManger).setOnClickListener(this);
		findViewById(R.id.btnDataManage).setOnClickListener(this);
		findViewById(R.id.btnBudget).setOnClickListener(this);
		findViewById(R.id.btnSetting).setOnClickListener(this);
		quickWriteBill_BTN = (ImageButton) findViewById(R.id.quickWriteBill_BTN);
		recoder_BTN = (ImageButton) findViewById(R.id.recoder_BTN);
		writeBill_btn = (Button) findViewById(R.id.writeBill_btn);
		message_BTN = (ImageButton) findViewById(R.id.message_BTN);
		billListView = (ListView) findViewById(R.id.billList);
		spending_this_month = (AutoAdjustTextView) findViewById(R.id.spending_this_month);
		spending_this_week = (AutoAdjustTextView) findViewById(R.id.spending_this_week);

	}
	void DoCheck(){
		new Thread() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Looper.prepare();
				// 此处的Looper必须添加
			

				
				// 此处的Looper必须添加
				if(checkUpdate()){
					updatedialog.show();
				}
				
				
				
				Looper.loop();
			

				super.run();
			}
		}.start();
	}
	boolean checkUpdate() {

		
		// Sync2Server();
		// SyncFromServer();
		try {
			
			SharedPreferences sharedPreferences = getSharedPreferences(
					Constant.DeviceInfo, Context.MODE_PRIVATE);
			String version=sharedPreferences.getString(
					"version", "");
//			JSONArray updateArray = HttpTools
//					.HttpGetDataCheckVer(sharedPreferences.getString(
//							"deviceInfo", ""));
			JSONArray updateArray = HttpTools
					.HttpGetDataCheckVer(version);

			JSONObject updateArr = updateArray.getJSONObject(0);
			// .replace("\\/", "/"));
			Log.i("AboutActivity", updateArray.toString());
			Log.i("AboutActivity",
					updateArr.getString("updateUrl").replace("\\", ""));
			String updatecontent = updateArr.getString("updatecontent");
			if (!version.equals(updateArr.getString("version"))) {
				ShowTools.toastInThread(getString(R.string.softversion_newfind) + updateArr.getString("version"));
				// ShowTools.toast("发现新版本" + updatecontent);
		
				updatedialog=ShowDialog.buildUpdateDialog(MainActivity.this,
						updateArr.getString("version"), updatecontent,
						updateArr.getString("updateUrl").replace("\\", ""))
						;
				Log.i("xiawei", updatedialog.toString());
			return true;
			}else {
				return false;
			}
//			else if (!updateArr.getBoolean("update")) {
//				ShowTools.toastInThread("已安装最新版本："
//						+ updateArr.getString("version"));
//				// ShowTools.toast("发现新版本" + updatecontent);
//				return false;
//
//			} else {
//				ShowTools.toastInThread("检查更新出现异常");
//				// ShowTools.toast("发现新版本" + updatecontent);
//				return false;
//			}
		} catch (Exception e) {
			e.printStackTrace();
		
			//ShowTools.toastInThread("检测版本失败，请稍后重试");
			// TODO: handle exception
			return false;
		}finally{
			//init();
			}
		
	
	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		switch (arg0.getId()) {
		case R.id.btnDetails:
			startActivity(new Intent(MainActivity.this, NewBillActivity.class));
			break;
		case R.id.UserManger:
			startActivity(new Intent(MainActivity.this, LoginActivity.class));
			break;
		case R.id.btnDataManage:
			startActivity(new Intent(MainActivity.this, SyncActivity.class));
			break;
		case R.id.btnBudget:
			startActivity(new Intent(MainActivity.this, BudgetActivity.class));
			break;
		case R.id.btnSetting:
			startActivity(new Intent(MainActivity.this, AboutActivity.class));
			break;
		case R.id.quickWriteBill_BTN:
			startActivity(new Intent(MainActivity.this, NewBillActivity.class));
			break;
		case R.id.writeBill_btn:
			startActivity(new Intent(MainActivity.this, NewBillActivity.class));
			break;
//		case R.id.recoder_BTN:
//			ShowTools.toast("write");
//			break;
//		case R.id.message_BTN:
//			ShowTools.toast("message_BTN");
//			break;
//		case R.id.billMoneyTextView:
//			// ShowTools.toast(((TextView)(ListView)findViewById(R.id.RelativeLayout01).findViewById(R.id.ItemImage)).getText());
//			break;
		}
	}
}
